package com.max.api;


import com.max.common.LoginUserInfo;
import com.max.common.R;
import com.max.dto.LoginDTO;
import com.max.dto.UserRegisterDTO;
import com.max.service.IUserInfoService;
import com.max.utils.JwtUtils;
import io.swagger.annotations.Api;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户相关开放接口")
@RestController
@RequestMapping(value = "/open/user")
@Validated
public class UserOpenApi {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public R<?> register(@Valid @RequestBody UserRegisterDTO userRegisterDTO) {
        return R.result(userInfoService.register(userRegisterDTO));
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R<?> login(@Valid @RequestBody LoginDTO dto) {
        UsernamePasswordAuthenticationToken loginToken = new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(loginToken);
        if (authenticate == null) {
            return R.error("用户名或密码错误");
        }
        LoginUserInfo principal = (LoginUserInfo) authenticate.getPrincipal();
        //生成JWT TOKEN
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", principal.getUsername());
        claims.put("authorities", principal.getAuthorities());
        claims.put("userId", principal.getUserId());
        return R.ok(jwtUtils.createJWTToken(claims, principal.getUsername()));
    }


}
